package swagger

import (
	"encoding/json"
	"log"
	"os"
	"path/filepath"
	"strings"

	"easy-stock-analyzer/aktools/utility"
)

// GenerateSwaggerDocs 根据config.json动态生成Swagger文档
func GenerateSwaggerDocs() {
	// 读取配置
	cfg := utility.AkToolsCfg

	// 构建Swagger文档结构
	doc := map[string]interface{}{
		"swagger": "2.0",
		"info": map[string]string{
			"description": "用于股票数据查询的API服务",
			"title": "aktools API",
			"version": "1.0",
		},
		"host": "localhost:8088",
		"basePath": "/api",
		"paths": make(map[string]interface{}),
	}

	// 为每个API配置生成文档
	for key, config := range cfg {
		path := "/" + key
		doc["paths"].(map[string]interface{})[path] = map[string]interface{}{
			"get": map[string]interface{}{
				"summary": config.Description,
				"responses": map[string]interface{}{
					"200": map[string]interface{}{
						"description": "成功",
						"schema": buildResponseSchema(config),
					},
				},
			},
		}
		if params := buildParameters(config.Params); params != nil {
			doc["paths"].(map[string]interface{})[path].(map[string]interface{})["get"].(map[string]interface{})["parameters"] = params
		}
	}

	// 生成JSON文件
	jsonData, err := json.MarshalIndent(doc, "", "  ")
	if err != nil {
		log.Fatalf("生成JSON失败: %v", err)
	}

	// 写入文件
	docsDir := filepath.Join("docs")
	if err := os.MkdirAll(docsDir, 0755); err != nil {
		log.Fatalf("创建docs目录失败: %v", err)
	}

	if err := os.WriteFile(filepath.Join(docsDir, "swagger.json"), jsonData, 0644); err != nil {
		log.Fatalf("写入swagger.json失败: %v", err)
	}

	log.Println("成功生成Swagger文档")
}

// buildParameters 根据参数配置生成Swagger参数定义
func buildParameters(params map[string]utility.Param) []map[string]interface{} {
	var parameters []map[string]interface{}
	for paramName, paramValue := range params {
		parameters = append(parameters, map[string]interface{}{
			"name":     paramName,
			"in":       "query",
			"required": paramValue.Required,
			"type":     "string",
		})
	}
	if len(parameters) == 0 {
		return nil
	}
	return parameters
}

// buildResponseSchema 根据配置生成响应体结构
func buildResponseSchema(config utility.Config) map[string]interface{} {
	if config.BodyType == "items" {
		return map[string]interface{}{
			"type":       "object",
			"properties": buildProperties(config.Bodys),
		}
	}

	return map[string]interface{}{
		"type":  "array",
		"items": map[string]interface{}{
			"type":       "object",
			"properties": buildProperties(config.Bodys),
		},
	}
}

// buildProperties 根据字段映射生成属性定义
func buildProperties(bodys map[string]string) map[string]interface{} {
	properties := make(map[string]interface{})
	for _, dstName := range bodys {
		if dstName != "" {
			// 根据字段名推断数据类型
			fieldType := "string"
			exampleStr := "示例值"

			// 数字类型字段
			numberFields := []string{"price", "volume", "turnover", "change_rate", "change_price", "turnover_rate", "total_share", "float_share", "total_market_value", "float_market_value", "pe_", "pb", "peg", "pcf", "efficiency", "roe_", "net_profit_margin_", "total_asset_turnover_", "equity_multiplier_", "up_count", "limit_up_count", "real_limit_up_count", "st_limit_up_count", "down_count", "limit_down_count", "real_limit_down_count", "st_limit_down_count", "flat_count", "suspend_count", "activity_rate", "hold_amount", "hold_market_value", "hold_change_value", "hold_change_rate"}
			for _, prefix := range numberFields {
				if strings.Contains(dstName, prefix) {
					fieldType = "number"
					exampleStr = "100.00"
					break
				}
			}

			// 整数类型字段
			integerFields := []string{"count", "rank", "index"}
			for _, suffix := range integerFields {
				if len(dstName) >= len(suffix) && dstName[len(dstName)-len(suffix):] == suffix {
					fieldType = "integer"
					exampleStr = "1"
					break
				}
			}

			properties[dstName] = map[string]interface{}{
				"type":      fieldType,
				"example":   exampleStr,
			}
		}
	}
	return properties
}

func init() {
	
}